package com.suning.park.admin.mgr.park.controller;

import com.alibaba.fastjson.JSON;
import com.suning.park.dto.model.Park;
import com.suning.park.dto.model.ParkIntervalFeeRule;
import com.suning.park.dto.model.SysUser;
import com.suning.park.admin.util.JsonUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.admin.util.page.PageResult;
import com.suning.park.admin.base.IAbstractController;
import com.suning.park.admin.bean.Response;
import com.suning.park.admin.enums.YesOrNoEnum;
import com.suning.park.admin.mgr.park.service.IParkService;
import com.suning.park.admin.util.DateUtil;
import com.suning.park.admin.util.IdBuilder;
import com.suning.park.admin.util.StringUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 停车场
 * Created by Administrator on 2017/1/10.
 */
@Controller
@RequestMapping(value="/mgr/park", produces = { "application/json;charset=UTF-8" })
public class ParkController extends IAbstractController {

    private static final Logger logger = LoggerFactory.getLogger(ParkController.class);

    @Resource
    IParkService parkService;

    /**
     * 列表页面跳转
     * @param view
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(ModelAndView view) {
        logger.info("停车场列表页面跳转");
        view.setViewName("park/list");
        return view;
    }

    /**
     * 添加页面跳转
     * @param view
     * @return
     */
    @RequestMapping(value = "/addUI", method = RequestMethod.GET)
    public ModelAndView add(ModelAndView view) {
        logger.info("添加停车场页面跳转");
        view.setViewName("park/add");
        return view;
    }

    /**
     * 编辑页面跳转
     * @param view
     * @param id
     * @return
     */
    @RequestMapping(value = "/editUI/{id}", method = RequestMethod.GET)
    public ModelAndView editUI(ModelAndView view, @PathVariable("id") String id) throws Exception {
        logger.info("编辑停车场信息页面跳转，基础数据ID：{}", id);
        String rules = parkService.getParkIntervalFeeRules(id);
        view.addObject("park", parkService.selectByPrimaryKey(id));
        view.addObject("rules", rules);
        view.setViewName("park/edit");
        return view;
    }

    /**
     * 新增停车场
     * @param park
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody String add(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest  request,
            Park park,
            @RequestParam(value = "parkIntervalFeeRules", required = false) String parkIntervalFeeRules) throws Exception {
        logger.info("新增停车场信息：{}", JsonUtil.objectToJson(park));
        logger.info("停车场按时段信息：{}", JsonUtil.objectToJson(parkIntervalFeeRules));

        //获得登录用户
        SysUser sysUser = super.getCurrentUser(request);
        //上传停车场封面
        String parkConverPath = uploadFile(file, request);
        if(StringUtil.isNotBlank(parkConverPath)) {
            park.setParkConverPath(parkConverPath);
        }
        //获得停车场按时段计费规则集合
        List<ParkIntervalFeeRule> parkIntervalFeeRuleList = JSON.parseArray(parkIntervalFeeRules, ParkIntervalFeeRule.class);
        //新增停车场
        parkService.insert(park, parkIntervalFeeRuleList, sysUser.getUserId(), sysUser.getName());
        return Response.SUCCESS().toJson();
    }

    /**
     * 文件上传
     * @param file
     * @param request
     */
    private String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        if(file.isEmpty()) {
            return null;
        }
        String path = request.getSession().getServletContext().getRealPath("/hplus/parkImg/");
        //生成文件名
        StringBuffer fileName = new StringBuffer();
        fileName.append(DateUtil.currentDateyyMMdd()).append("_");
        fileName.append(IdBuilder.getID()).append(".");
        fileName.append(FilenameUtils.getExtension(file.getOriginalFilename()));
        File targetFile = new File(path, fileName.toString());
        file.transferTo(targetFile);
        return fileName.toString();
    }

    /**
     * 编辑停车场信息
     * @param park
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public  @ResponseBody String edit(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletRequest request,
            Park park,
            @RequestParam(value = "parkIntervalFeeRules", required = false) String parkIntervalFeeRules) throws Exception {
        logger.info("编辑停车场信息：{}", JsonUtil.objectToJson(park));

        //获得登录用户
        SysUser sysUser = super.getCurrentUser(request);
        //上传停车场封面
        String parkConverPath = uploadFile(file, request);
        if (StringUtil.isNotBlank(parkConverPath)) {
            park.setParkConverPath(parkConverPath);
        }
        //获得停车场按时段计费规则集合
        if (StringUtil.isNotBlank(parkIntervalFeeRules)){
            List<ParkIntervalFeeRule> parkIntervalFeeRuleList = JSON.parseArray(parkIntervalFeeRules, ParkIntervalFeeRule.class);
            //批量编辑停车场按时段计费规则
            parkService.batchInsertParkIntervalFeeRule(park.getId(), parkIntervalFeeRuleList, sysUser.getUserId(), sysUser.getName());
         }
        //更新停车场
        parkService.update(park, sysUser.getUserId(), sysUser.getName());
        return Response.SUCCESS().toJson();
    }

    /**
     * 获得列表
     * @param draw
     * @param pageInfo
     * @param property
     * @param parkType
     * @param businessEntity
     * @param isFee
     * @param parkName
     * @return
     */
    @RequestMapping(value = "/ajaxList")
    public @ResponseBody
    PageResult ajaxList(
            @RequestParam(value = "draw") int draw, PageInfo pageInfo,
            @RequestParam(value = "property", required = false) String property,
            @RequestParam(value = "parkType", required = false) String parkType,
            @RequestParam(value = "businessEntity", required = false) String businessEntity,
            @RequestParam(value = "isFee", required = false) String isFee,
            @RequestParam(value = "parkName", required = false) String parkName,
            @RequestParam(value = "integralBodyType", required = false) String integralBodyType) throws Exception {
        logger.info("停车场管理列表查询， 产权方：{}，业态：{}，经营主体：{}，是否收费：{}，停车场名称：{}，积分主体类型：{}",
                new Object[]{ property, parkType, businessEntity, isFee, parkName, integralBodyType});
        Map<String, Object> params = getAjaxListParmas(property, parkType, businessEntity, isFee, parkName, integralBodyType);
        pageInfo = parkService.queryByPage(params, pageInfo);
        return new PageResult(pageInfo, draw);
    }

    /**
     * 查询条件
     * @param property
     * @param parkType
     * @param businessEntity
     * @param isFee
     * @param parkName
     * @param integralBodyType
     * @return
     */
    private Map<String, Object> getAjaxListParmas(String property, String parkType, String businessEntity, String isFee, String parkName, String integralBodyType) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(property)) {
            params.put("property", property.trim());
        }
        if (StringUtils.isNotBlank(parkType)) {
            params.put("parkType", parkType.trim());
        }
        if (StringUtils.isNotBlank(businessEntity)) {
            params.put("businessEntity", businessEntity.trim());
        }
        if (StringUtils.isNotBlank(isFee)) {
            params.put("isFee", isFee.trim());
        }
        if (StringUtils.isNotBlank(parkName)) {
            params.put("parkName", parkName.trim());
        }
        if (StringUtils.isNotBlank(integralBodyType)) {
            params.put("integralBodyType", integralBodyType.trim());
        }
        return params;
    }

    /**
     * 获得停车场列表
     * @return
     */
    @RequestMapping(value = "/getParkList", method = RequestMethod.GET)
    public @ResponseBody Object getList() throws Exception {
        logger.info("获得停车场列表");
        return Response.SUCCESS().put("parkList", parkService.selectAllList()).toJson();
    }

    /**
     * 启用停车场
     * @param list
     * @return
     */
    @RequestMapping(value = "/enable")
    public @ResponseBody Object enable(@RequestParam(required = false, value = "list[]") List<String> list) throws Exception {
        logger.info("启用停车场，Ids：{}", JsonUtil.objectToJson(list));
        parkService.updateStateByIds(list, YesOrNoEnum.YES.getValue());
        return Response.SUCCESS().toJson();
    }

    /**
     * 禁用停车场
     * @param list
     * @return
     */
    @RequestMapping(value = "/disable")
    public @ResponseBody String disable(@RequestParam(required = false, value = "list[]") List<String> list) throws Exception {
        logger.info("禁用停车场，Ids：{}", JsonUtil.objectToJson(list));
        parkService.updateStateByIds(list, YesOrNoEnum.NO.getValue());
        return Response.SUCCESS().toJson();
    }
}
